package cn.bqjr.eily.shiro.spring.boot.filter;

import cn.bqjr.eily.utils.I18nUtils;
import cn.bqjr.eily.utils.StringUtils;
import cn.bqjr.eily.web.exception.exclass.UnAuthorizedException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Token过滤器
 */
public class AccessTokenFilter extends AbstractAccessControlFilter {

    private String tokenHeaderName = null;

    public AccessTokenFilter(String tokenHeaderName) {
        this.tokenHeaderName = tokenHeaderName;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        throw new UnAuthorizedException(I18nUtils.getMsg("error.authorized.inValidToken"));
    }

    /**
     * 是否为有效Token
     * @param request
     * @return
     */
    private boolean isValidAccessToken(HttpServletRequest request) {
        String accessToken = request.getHeader(tokenHeaderName);
        if (StringUtils.isBlank(accessToken)) {
            return false;
        }

        Subject subject = SecurityUtils.getSubject();
        if (null != subject) {
            return subject.isAuthenticated(); //是否已认证通过
        }

        return false;
    }

    @Override
    protected boolean doIsAccessAllowed(HttpServletRequest request,
                                        HttpServletResponse response, Object o) {
        if (isValidAccessToken(request)) {
            return true;
        }
        return false;
    }
}
